<?php
/*
stardevelop.com Live Help
International Copyright stardevelop.com

You may not distribute this program in any manner,
modified or otherwise, without the express, written
consent from stardevelop.com

You may make modifications, but only for your own 
use and within the confines of the License Agreement.
All rights reserved.

Selling the code for this program without prior 
written consent is expressly forbidden. Obtain 
permission before redistributing this program over 
the Internet or in any other medium.  In all cases 
copyright and header must remain intact.  
*/
include('../include/database.php');
include('../include/class.mysql.php');
include('../include/config.php');
include('../include/version.php');
include('../include/functions.php');

if (!isset($_REQUEST['Username'])){ $_REQUEST['Username'] = ''; }
if (!isset($_REQUEST['Password'])){ $_REQUEST['Password'] = ''; }
$_OPERATOR = array();

if (IsAuthorized() == true) {

	switch ($_SERVER['QUERY_STRING']) {
		case 'Login':
			Login();
			break;
		case 'Users':
			Users();
			break;
		case 'Visitors':
			Visitors();
			break;
		case 'Version':
			Version();
			break;
		case 'Settings':
			Settings();
			break;
		case 'InitaliseChat':
			InitaliseChat();
			break;
		case 'Chat':
			Chat();
			break;
		case 'Operators':
			Operators();
			break;
		case 'Statistics':
			Statistics();
			break;
		case 'History':
			History();
			break;
		case 'Send':
			Send();
			break;
		case 'EmailChat':
			EmailChat();
			break;
		default:
			if (strpos(php_sapi_name(), 'cgi') === false ) { header('HTTP/1.0 403 Forbidden'); } else { header('Status: 403 Forbidden'); }
			break;
	}
	
} else {

	switch ($_SERVER['QUERY_STRING']) {
		case 'Version':
			Version();
			break;
	}

	if (strpos(php_sapi_name(), 'cgi') === false ) { header('HTTP/1.0 403 Forbidden'); } else { header('Status: 403 Forbidden'); }
}

exit();


function IsAuthorized() {

	global $_OPERATOR;
	global $SQL;
	global $table_prefix;

	if ($_REQUEST['Username'] != '' && $_REQUEST['Password'] != '') { 

		$query = "SELECT `id`, `firstname`, `lastname`, `department`, `datetime`, `privilege` FROM " . $table_prefix . "users WHERE `username` REGEXP BINARY '^" . $_REQUEST['Username'] . "$' AND `password` = '" . $_REQUEST['Password'] . "'";
		$row = $SQL->selectquery($query);
		if (is_array($row)) {
			$_OPERATOR['ID'] = $row['id'];
			$_OPERATOR['USERNAME'] = $_REQUEST['Username'];
			$_OPERATOR['PASSWORD'] = $_REQUEST['Password'];
			$_OPERATOR['NAME'] = $row['firstname'] . ' ' . $row['lastname'];
			$_OPERATOR['DEPARMENT'] = $row['department'];
			$_OPERATOR['DATETIME'] = $row['datetime'];
			$_OPERATOR['PRIVILEGE'] = $row['privilege'];
			return true;
		}
	}
	return false;
}

function Login() {

	global $_OPERATOR;
	global $SQL;
	global $table_prefix;
	global $web_application_version;

	if (!isset($_REQUEST['Action'])){ $_REQUEST['Action'] = ''; }

	switch ($_REQUEST['Action']) {
		case 'Online':
			$status = 1;
			break;
		case 'BRB':
			$status = 2;
			break;
		case 'Away':
			$status = 3;
			break;
		default:
			$status = 0;
			break;
	}
	
	// Update operator session to database
	$query = "UPDATE " . $table_prefix . "users SET `datetime` = NOW(), `refresh` = NOW(), `status` = '$status' WHERE `id` = '" . $_OPERATOR['ID'] . "'";
	$SQL->miscquery($query);

	header('Content-type: text/xml; charset=utf-8');
	echo('<?xml version="1.0" encoding="utf-8"?>' . "\n");
?>
<Login xmlns="urn:LiveHelp" ID="<?php echo($_OPERATOR['ID']); ?>" Version="<?php echo($web_application_version); ?>" Name="<?php echo(xmlattribinvalidchars($_OPERATOR['NAME'])); ?>" Access="<?php echo($_OPERATOR['PRIVILEGE']); ?>"/>
<?php

}

function Users() {
	
	global $_OPERATOR;
	global $_SETTINGS;
	global $SQL;
	global $table_prefix;
	global $connection_timeout;
	
	if (!isset($_REQUEST['Action'])){ $_REQUEST['Action'] = ''; }
	if (!isset($_REQUEST['ID'])){ $_REQUEST['ID'] = ''; }
	if (!isset($_REQUEST['Transfer'])){ $_REQUEST['Transfer'] = ''; }
	
	// Update the username, password and make no mode changes
	$query = "UPDATE " . $table_prefix . "users SET `refresh` = NOW() WHERE `id` = '" . $_OPERATOR['ID'] . "'";
	$SQL->miscquery($query);
	
	// Check for actions and process
	if ($_REQUEST['Action'] == 'Accept' && $_REQUEST['ID'] != '0') {
	
		// Check if already assigned to a Support operator
		$query = "SELECT `active` FROM " . $table_prefix . "sessions WHERE `id` = '" . $_REQUEST['ID'] . "'";
		$row = $SQL->selectquery($query);
		if (is_array($row)) {
			if ($row['active'] == '0' || $row['active'] == '-2') {
	
				// Update the active flag of the guest user to the ID of their supporter and update the support_user to the username of their supporter
				$query = "UPDATE " . $table_prefix . "sessions SET `active` = '" . $_OPERATOR['ID'] . "' WHERE `id` = '" . $_REQUEST['ID'] . "'";
				$SQL->miscquery($query);
	
			}
		}
	}
	elseif ($_REQUEST['Action'] == 'Close' && $_REQUEST['ID'] != '0') {
	
		// Update active of user to -3 to remove from users panel
		$query = "UPDATE " . $table_prefix . "sessions SET `active` = '-1' WHERE `id` = '" . $_REQUEST['ID'] . "'";
		$SQL->miscquery($query);
		
	}
	elseif ($_REQUEST['Action'] == 'Transfer' && $_REQUEST['ID'] != '0' && $_REQUEST['Transfer'] != '0') {
	
		$query = "UPDATE " . $table_prefix . "sessions SET `datetime` = NOW(), `active`= '-2', `transfer` = '" . $_REQUEST['Transfer'] . "' WHERE `id` = '" . $_REQUEST['ID'] . "'";
		$SQL->miscquery($query);
		
	}
	elseif ($_REQUEST['Action'] == 'Hide' && $_REQUEST['ID'] != '0') {
	
		// Update active of user to -3 to remove from users panel
		$query = "UPDATE " . $table_prefix . "sessions SET `active` = '-3' WHERE `id` = '" . $_REQUEST['ID'] . "'";
		$SQL->miscquery($query);
		
	}
	elseif ($_REQUEST['Action'] == 'Hidden' || $_REQUEST['Action'] == 'Offline') {
		// Update the username, password and change to hidden mode
		$query = "UPDATE " . $table_prefix . "users SET `refresh` = NOW(), `status` = '0' WHERE `id` = '" . $_OPERATOR['ID'] . "'";
		$SQL->miscquery($query);
	}
	elseif ($_REQUEST['Action'] == 'Online') {
		// Update the username, password and change to online mode
		$query = "UPDATE " . $table_prefix . "users SET `refresh` = NOW(), `status` = '1' WHERE `id` = '" . $_OPERATOR['ID'] . "'";
		$SQL->miscquery($query);
	}
	elseif ($_REQUEST['Action'] == 'BRB') {
		// Update the username, password and change to be right back mode
		$query = "UPDATE " . $table_prefix . "users SET `refresh` = NOW(), `status` = '2' WHERE `id` = '" . $_OPERATOR['ID'] . "'";
		$SQL->miscquery($query);
	}
	elseif ($_REQUEST['Action'] == 'Away') {
		// Update the username, password and change to be right back mode
		$query = "UPDATE " . $table_prefix . "users SET `refresh` = NOW(), `status` = '3' WHERE `id` = '" . $_OPERATOR['ID'] . "'";
		$SQL->miscquery($query);
	}
	
	header('Content-type: text/xml; charset=utf-8');
	echo('<?xml version="1.0" encoding="utf-8"?>' . "\n");
?>
<Users xmlns="urn:LiveHelp">
<?php
	// ONLINE ADMIN USERS QUERY
	$query = "SELECT `id`, `username`, `status` FROM " . $table_prefix . "users WHERE (UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(`refresh`)) < '$connection_timeout' AND (`status` = '1' OR `status` = '2' OR `status` = '3') ORDER BY `username`";
	$rows = $SQL->selectall($query);
	
	if (is_array($rows)) {
?>
<Staff>
<?php
		foreach ($rows as $key => $row) {
			if (is_array($row)) {
				$id = $row['id'];
				$status = $row['status'];
				$username = $row['username'];
				
				// Count the total NEW messages that have been sent to the current login
				$query = "SELECT max(`id`) FROM " . $table_prefix . "administration WHERE `username` = '$username' AND `user` = '" . $_OPERATOR['ID'] . "' AND (UNIX_TIMESTAMP(`datetime`) - UNIX_TIMESTAMP('" . $_OPERATOR['DATETIME'] . "')) > '0'";
				$row = $SQL->selectquery($query);
				if (is_array($row)) {
					$messages = $row['max(`id`)'];
				}
?>
<User ID='<?php echo($id); ?>' <?php if ($messages != '') { ?>Messages='<?php echo($messages); ?>' <?php } ?>Status='<?php echo($status); ?>'><?php echo(xmlelementinvalidchars($username)); ?></User>
<?php
			}
		}
?>
</Staff>
<?php
	} else {
?>
<Staff/>
<?php
	}
	
	// ONLINE GUEST USERS QUERY
	$query = "SELECT `id`, `username` FROM " . $table_prefix . "sessions WHERE (UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(`refresh`)) < '$connection_timeout' AND `active` = '" . $_OPERATOR['ID'] . "' ORDER BY `username`";
	$rows = $SQL->selectall($query);
	
	if (is_array($rows)) {
?>
<Online>
<?php
		foreach ($rows as $key => $row) {
			if (is_array($row)) {
				$id = $row['id'];
				$username = $row['username'];
				
				// Count the total NEW messages that have been sent to the current login
				$query = "SELECT max(`id`) FROM " . $table_prefix . "messages WHERE `session` = '$id' AND `status` <= '3' AND (UNIX_TIMESTAMP(`datetime`) - UNIX_TIMESTAMP('" . $_OPERATOR['DATETIME'] . "')) > '0'";
				$row = $SQL->selectquery($query);
				if (is_array($row)) {
					$messages = $row['max(`id`)'];
				}
?> 
<User ID='<?php echo($id); ?>'<?php if ($messages != '') { ?> Messages='<?php echo($messages); ?>'<?php } ?>><?php echo(xmlelementinvalidchars($username)); ?></User>
<?php
			}
		}
?>
</Online>
<?php
	}
	
	// PENDING USERS QUERY displays pending users not logged in on users users table depending on department settings
	if ($_SETTINGS['DEPARTMENTS'] == true) {
		$sql = departmentsSQL($_OPERATOR['DEPARMENT']);
		$query = "SELECT DISTINCT `id`, `username` FROM " . $table_prefix . "sessions WHERE (UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(`refresh`)) < '$connection_timeout' AND `active` = '0' AND $sql ORDER BY `username`";
	}
	else {
		$query = "SELECT DISTINCT `id`, `username` FROM " . $table_prefix . "sessions WHERE (UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(`refresh`)) < '$connection_timeout' AND `active` = '0' ORDER BY `username`";
	}
	$rows = $SQL->selectall($query);
	
	if (is_array($rows)) {
?>
<Pending>
<?php
		foreach ($rows as $key => $row) {
			if (is_array($row)) {
				$id = $row['id'];
				$username = $row['username'];
?>
<User ID='<?php echo($id); ?>'><?php echo(xmlelementinvalidchars($username)); ?></User>
<?php
			}
		}
?>
</Pending>
<?php
	}
	
	// TRANFERRED USERS QUERY displays transferred users not logged in on users users table depending on department settings
	$query = "SELECT DISTINCT `id`, `username` FROM " . $table_prefix . "sessions WHERE (UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(`refresh`)) < '$connection_timeout' AND `active` = '-2' AND `transfer` = '" . $_OPERATOR['ID'] . "' ORDER BY `username`";
	$rows = $SQL->selectall($query);
	
	if (is_array($rows)) {
?>
<Transferred>
<?php
		foreach ($rows as $key => $row) {
			if (is_array($row)) {
				$id = $row['id'];
				$username = $row['username'];
?> 
<User ID='<?php echo($id); ?>'><?php echo(xmlelementinvalidchars($username)); ?></User>
<?php
			}
		}
?>
</Transferred>
<?php
	}
?>
</Users>
<?php
}

function Visitors() {

	global $_OPERATOR;
	global $SQL;
	global $table_prefix;
	global $timezonehours;
	global $timezoneminutes;

	if (!isset($_REQUEST['Action'])){ $_REQUEST['Action'] = ''; }
	if (!isset($_REQUEST['Request'])){ $_REQUEST['Request'] = ''; }
	if (!isset($_REQUEST['Record'])){ $_REQUEST['Record'] = ''; }
	
	if ($_REQUEST['Action'] == 'Initiate' && $_OPERATOR['PRIVILEGE'] < 4) {
	
		if ($_REQUEST['Request'] != '') {
			// Update active field of user to the ID of the operator that initiated support
			$query = "UPDATE " . $table_prefix . "requests SET `initiate` = '" . $_OPERATOR['ID'] . "' WHERE `id` = '" . $_REQUEST['Request'] . "'";
			$SQL->miscquery($query);
		}
		else {
			// Initiate chat request with all visitors
			$query = "UPDATE " . $table_prefix . "requests SET `initiate` = '" . $_OPERATOR['ID'] . "'";
			$SQL->miscquery($query);
		}
		
		header('Content-type: text/xml; charset=utf-8');
		echo('<?xml version="1.0" encoding="utf-8"?>' . "\n");
?>
<Visitors xmlns="urn:LiveHelp"/>
<?php
		exit();
	}
	elseif ($_REQUEST['Action'] == 'Remove' && $_OPERATOR['PRIVILEGE'] < 3) {
	
		if ($_REQUEST['Request'] != '') {
			// Update active field of user to the ID of the operator that initiated support
			$query = "UPDATE " . $table_prefix . "requests SET `status` = '1' WHERE `id` = '" . $_REQUEST['Request'] . "'";
			$SQL->miscquery($query);
		}
		
		header('Content-type: text/xml; charset=utf-8');
		echo('<?xml version="1.0" encoding="utf-8"?>' . "\n");
?>
<Visitors xmlns="urn:LiveHelp"/>
<?php
		exit();
	}

	$query = "SELECT *, ((UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(`datetime`))) AS `sitetime`, ((UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(`request`))) AS `pagetime` FROM " . $table_prefix . "requests WHERE `refresh` > NOW() - INTERVAL 45 SECOND AND `status` = '0' ORDER BY `id` ASC";
	$rows = $SQL->selectall($query);
	if (is_array($rows)) {
	
		$last = 0; $total= 0; $pageviews = 0;
	
		foreach ($rows as $key => $row) {
			if (is_array($row)) {
				$last = $row['id'];
				$total += 1;
				$pageviews += substr_count($row['path'], '; ') + 1;
			}
		}

		if ($total > 0) {
			while ($total <= $_REQUEST['Record']) {
				$_REQUEST['Record'] = $_REQUEST['Record'] - 6;
			}
		} else {
			$_REQUEST['Record'] = 0;
		}
		
		header('Content-type: text/xml; charset=utf-8');
		echo('<?xml version="1.0" encoding="utf-8"?>' . "\n");
?>
<Visitors xmlns="urn:LiveHelp" TotalVisitors="<?php echo($total); ?>" LastVisitor="<?php echo($last); ?>" PageViews="<?php echo($pageviews); ?>">
<?php
	
		$initiated_default_label = 'Live Help Request has not been Initiated';
		$initiated_sending_label = 'Sending the Initiate Live Help Request...';
		$initiated_waiting_label = 'Waiting on the Initiate Live Help Reply...';
		$initiated_accepted_label = 'Initiate Live Help Request was ACCEPTED';
		$initiated_declined_label = 'Initiate Live Help Request was DECLINED';
		$initiated_chatting_label = 'Currently chatting to Operator';
		$initiated_chatted_label = 'Already chatted to an Operator';
		$initiated_pending_label = 'Currently Pending for Live Help';
		
		$rating_label = 'Rating';			
		$unavailable_label = 'Unavailable';
		
		foreach ($rows as $key => $row) {
			if (is_array($row)) {
				if ($key >= $_REQUEST['Record'] && $key < $_REQUEST['Record'] + 6) {
					$current_request_id = $row['id'];
					$current_request_ip_address = $row['ipaddress'];
					$current_request_user_agent = $row['useragent'];
					$current_request_resolution = $row['resolution'];
					$current_request_country = $row['country'];
					$current_request_current_page = $row['url'];
					$current_request_current_page_title = $row['title'];
					$current_request_referrer = $row['referrer'];
					$current_request_pagetime = $row['pagetime'];
					$current_request_page_path = $row['path'];
					$current_request_sitetime = $row['sitetime'];
					$current_request_request_flag = $row['initiate'];
					
			
					// Get the supporters name of the chat request if currently chatting.
					$query = "SELECT `id`, `username`, `department`, `rating`, `active` FROM " . $table_prefix . "sessions WHERE `request` = '$current_request_id' ORDER BY `datetime` DESC LIMIT 1";
					$row = $SQL->selectquery($query);
					if (is_array($row)) {
					
						$current_session_id = $row['id'];
						$current_session_username = $row['username'];
						$current_session_department = $row['department'];
						$current_session_rating = $row['rating'];
						$current_session_active = $row['active'];
						
						if ($current_session_active == '-1' || $current_session_active == '-3') {
							// Display the rating of the ended chat request
							if ($current_session_rating > 0) {
								$current_request_initiate_status = $initiated_chatted_label . ' - ' . $rating_label . ' (' . $current_session_rating . '/5)';
							}
							else {
								$current_request_initiate_status = $initiated_chatted_label;
							}
						}
						else {
							if ($current_session_active > 0) {
								// Get the supporters name of the chat request if currently chatting.
								$query = "SELECT `firstname`, `lastname` FROM " . $table_prefix . "users WHERE `id` = '$current_session_active'";
								$row = $SQL->selectquery($query);
								if (is_array($row)) {
									$current_session_support_name = $row['firstname'] . ' ' . $row['lastname'];
									$current_request_initiate_status = $initiated_chatting_label . ' (' . $current_session_support_name . ')';
								}
								else {
									$current_request_initiate_status = $initiated_chatting_label . ' (' . $unavailable_label . ')';
								}
							}
							else {
								if ($current_session_department != '') {
									$current_request_initiate_status = $initiated_pending_label . ' (' . $current_session_department . ')';
								}
								else {
									$current_request_initiate_status = $initiated_pending_label;
								}
							}
						}
					}
					else {
						$current_session_id = 0;
						$current_session_username = '';
						$current_session_active = '';
						
						// The Site Visitor has not been sent an Initiate Chat request..
						if ($current_request_request_flag == '0'){
							$current_request_initiate_status = $initiated_default_label;
						}
						// displayed the request..
						elseif ($current_request_request_flag == '-1') {
							$current_request_initiate_status = $initiated_waiting_label;
						}
						// accepted the request..
						elseif ($current_request_request_flag == '-2') {
							$current_request_initiate_status = $initiated_accepted_label;
						}
						// declined the request..
						elseif ($current_request_request_flag == '-3') {
							$current_request_initiate_status = $initiated_declined_label;
						}
						// sent a request and waiting to open on screen..
						else {
							$current_request_initiate_status = $initiated_sending_label;
						}
					}
					
					if ($current_request_current_page == '') {
						$current_request_current_page = $unavailable_label;
					}
					
					// Set the referrer as approriate
					if ($current_request_referrer != '' && $current_request_referrer != 'false') {
						$current_request_referrer_result = $current_request_referrer;
					}
					elseif ($current_request_referrer == false) {
						$current_request_referrer_result = 'Direct Visit / Bookmark';
					}
					else {
						$current_request_referrer_result = $unavailable_label;
					}
?>
<Visitor ID="<?php echo($current_request_id); ?>" Session="<?php echo($current_session_id); ?>" Active="<?php echo($current_session_active); ?>" Username="<?php echo(xmlattribinvalidchars($current_session_username)); ?>">
<Hostname><?php echo(xmlelementinvalidchars($current_request_ip_address)); ?></Hostname>
<Country><?php echo($current_request_country); ?></Country>
<UserAgent><?php echo(xmlelementinvalidchars($current_request_user_agent)); ?></UserAgent>
<Resolution><?php echo(xmlelementinvalidchars($current_request_resolution)); ?></Resolution>
<CurrentPage><?php echo(xmlelementinvalidchars($current_request_current_page)); ?></CurrentPage>
<CurrentPageTitle><?php echo(xmlelementinvalidchars($current_request_current_page_title)); ?></CurrentPageTitle>
<Referrer><?php echo(xmlelementinvalidchars($current_request_referrer_result)); ?></Referrer>
<TimeOnPage><?php echo($current_request_pagetime); ?></TimeOnPage>
<ChatStatus><?php echo(xmlelementinvalidchars($current_request_initiate_status)); ?></ChatStatus>
<PagePath><?php echo(xmlelementinvalidchars($current_request_page_path)); ?></PagePath>
<TimeOnSite><?php echo($current_request_sitetime); ?></TimeOnSite>
</Visitor>
<?php
				}
			}
		}
?>
</Visitors>
<?php
	}
	else {
		header('Content-type: text/xml; charset=utf-8');
		echo('<?xml version="1.0" encoding="utf-8"?>' . "\n");
?>
<Visitors xmlns="urn:LiveHelp"/>
<?php
	}
}

function Version() {

	global $_OPERATOR;
	global $SQL;
	global $table_prefix;
	global $windows_application_version;

	if (!isset($_REQUEST['Windows'])){ $_REQUEST['Windows'] = ''; }
	if ($_REQUEST['Windows'] == $windows_application_version) { $result = 'true'; } else { $result = 'false'; }
	
	header('Content-type: text/xml; charset=utf-8');
	echo('<?xml version="1.0" encoding="utf-8"?>' . "\n");
?>
<Version xmlns="urn:LiveHelp" Web="" Windows="<?php echo($result); ?>"/>
<?php

	exit();
}

function Settings() {

	global $_OPERATOR;
	global $_SETTINGS;
	global $SQL;
	global $table_prefix;

	// Save Settings if authorized
	if ($_OPERATOR['PRIVILEGE'] < 2) {
	
		//for every post value check all the lines and update them.
		foreach ($_REQUEST as $key => $value) {
			//discard the unused post values ie submit buttons and save indict.
			if ($key != 'SAVE' && $key != 'Submit') { 
				$query = "UPDATE " . $table_prefix . "settings SET `value` = '$value' WHERE `name` = '$key'";
				$SQL->miscquery($query);
			}
		}
		
		$query = "SELECT `name`, `value` FROM " . $table_prefix . "settings";
		$rows = $SQL->selectall($query);
		if (is_array($rows)) {
			$_SETTINGS = array();
			foreach ($rows as $key => $row) {
				if (is_array($row)) {
					$_SETTINGS[strtoupper($row['name'])] = $row['value'];
				}
			}
		}
	}
	
	// Check available language packs
	$languages = file('../locale/i18n.txt');
	$available_languages = '';
	foreach ($languages as $key => $line) {
		$i18n = split(',', $line);
		$code = trim($i18n[0]);
		$available = file_exists('../locale/' . $code . '/guest.php');
		if ($available) {
			if ($available_languages == '') {
				$available_languages .= $code;
			}
			else {
				$available_languages .=  ', ' . $code;
			}
		}
	}
	
	header('Content-type: text/xml; charset=utf-8');
	echo('<?xml version="1.0" encoding="utf-8"?>' . "\n");
?>
<Settings xmlns="urn:LiveHelp">
<Domain><?php echo(xmlelementinvalidchars($_SETTINGS['DOMAIN'])); ?></Domain>
<SiteAddress><?php echo(xmlelementinvalidchars($_SETTINGS['URL'])); ?></SiteAddress>
<Email><?php echo(xmlelementinvalidchars($_SETTINGS['EMAIL'])); ?></Email>
<Name><?php echo(xmlelementinvalidchars($_SETTINGS['NAME'])); ?></Name>
<Logo><?php echo(xmlelementinvalidchars($_SETTINGS['LOGO'])); ?></Logo>
<WelcomeMessage><?php echo(xmlelementinvalidchars($_SETTINGS['INTRODUCTION'])); ?></WelcomeMessage>
<Smilies Guest="<?php echo($_SETTINGS['GUESTSMILIES']); ?>" Operator="<?php echo($_SETTINGS['OPERATORSMILIES']); ?>" />
<Font Size="<?php echo(xmlattribinvalidchars($_SETTINGS['FONTSIZE'])); ?>" Color="<?php echo(xmlattribinvalidchars($_SETTINGS['FONTCOLOR'])); ?>" LinkColor="<?php echo(xmlattribinvalidchars($_SETTINGS['LINKCOLOR'])); ?>"><?php echo(xmlattribinvalidchars($_SETTINGS['FONT'])); ?></Font>
<ChatFont Size="<?php echo(xmlattribinvalidchars($_SETTINGS['CHATFONTSIZE'])); ?>" SentColor="<?php echo(xmlattribinvalidchars($_SETTINGS['SENTFONTCOLOR'])); ?>" ReceivedColor="<?php echo(xmlattribinvalidchars($_SETTINGS['RECEIVEDFONTCOLOR'])); ?>"><?php echo(xmlelementinvalidchars($_SETTINGS['CHATFONT'])); ?></ChatFont>
<BackgroundColor><?php echo(xmlelementinvalidchars($_SETTINGS['BACKGROUNDCOLOR'])); ?></BackgroundColor>
<OnlineLogo><?php echo(xmlelementinvalidchars($_SETTINGS['ONLINELOGO'])); ?></OnlineLogo>
<OfflineLogo><?php echo(xmlelementinvalidchars($_SETTINGS['OFFLINELOGO'])); ?></OfflineLogo>
<OfflineEmailLogo><?php echo(xmlelementinvalidchars($_SETTINGS['OFFLINEEMAILLOGO'])); ?></OfflineEmailLogo>
<BeRightBackLogo><?php echo(xmlelementinvalidchars($_SETTINGS['BERIGHTBACKLOGO'])); ?></BeRightBackLogo>
<AwayLogo><?php echo(xmlelementinvalidchars($_SETTINGS['AWAYLOGO'])); ?></AwayLogo>
<LoginDetails Enabled="<?php echo($_SETTINGS['LOGINDETAILS']); ?>" Required="<?php echo(xmlattribinvalidchars($_SETTINGS['REQUIREGUESTDETAILS'])); ?>" Email="<?php echo($_SETTINGS['LOGINEMAIL']); ?>" Question="<?php echo($_SETTINGS['LOGINQUESTION']); ?>"/>
<OfflineEmail Enabled="<?php echo($_SETTINGS['OFFLINEEMAIL']); ?>" Redirect="<?php echo(xmlattribinvalidchars($_SETTINGS['OFFLINEEMAILREDIRECT'])); ?>"/>
<SecurityCode Enabled="<?php echo($_SETTINGS['SECURITYCODE']); ?>"/>
<Departments Enabled="<?php echo($_SETTINGS['DEPARTMENTS']); ?>"/>
<Timezone><?php echo(xmlelementinvalidchars($_SETTINGS['TIMEZONE'])); ?></Timezone>
<Language Available="<?php echo(xmlattribinvalidchars($available_languages)); ?>"><?php echo(xmlelementinvalidchars($_SETTINGS['LOCALE'])); ?></Language>
<InitiateChat Vertical="<?php echo(xmlattribinvalidchars($_SETTINGS['INITIATECHATVERTICAL'])); ?>" Horizontal="<?php echo(xmlattribinvalidchars($_SETTINGS['INITIATECHATHORIZONTAL'])); ?>"/>
<ChatUsername Enabled="<?php echo($_SETTINGS['CHATUSERNAME']); ?>"/>
<Campaign Link="<?php echo(xmlattribinvalidchars($_SETTINGS['CAMPAIGNLINK'])); ?>"><?php echo(xmlelementinvalidchars($_SETTINGS['CAMPAIGNIMAGE'])); ?></Campaign>
<IP2Country Enabled="<?php echo($_SETTINGS['IP2COUNTRY']); ?>"/>
<P3P><?php echo(xmlelementinvalidchars($_SETTINGS['P3P'])); ?></P3P>
<SMTP Enabled="<?php echo($_SETTINGS['SMTP']); ?>">
<Server Port="<?php echo(xmlattribinvalidchars($_SETTINGS['SMTPPORT'])); ?>"><?php echo(xmlattribinvalidchars($_SETTINGS['SMTPSERVER'])); ?></Server>
<Email><?php echo(xmlelementinvalidchars($_SETTINGS['SMTPEMAIL'])); ?></Email>
</SMTP>
<Code>
<Head><![CDATA[<?php include('../include/script.php'); ?>]]></Head>
<Body><![CDATA[<?php include('../include/tracking.php'); ?>]]></Body>
<Image><![CDATA[<?php include('../include/image.php'); ?>]]></Image>
</Code>
</Settings>
<?php

}

function InitaliseChat() {

	global $_OPERATOR;
	global $_SETTINGS;
	global $SQL;
	global $table_prefix;

	if (!isset($_REQUEST['ID'])){ $_REQUEST['ID'] = ''; }
	if (!isset($_REQUEST['Message'])){ $_REQUEST['Message'] = ''; }

	$query = "SELECT `email`, `question`, `server`, `department`, `typing`, `active` FROM " . $table_prefix . "sessions WHERE `id` = '" . $_REQUEST['ID'] . "'";
	$row = $SQL->selectquery($query);
	if (is_array($row)) {
		$email = $row['email'];
		$question = $row['question'];
		$server = $row['server'];
		$department = $row['department'];
		$typing = $row['typing'];
		$active = $row['active'];
	}

	$query = "SELECT `id`, `session`, `username`, `message`, `align`, `status` FROM " . $table_prefix . "messages WHERE `session` = '" . $_REQUEST['ID'] . "' AND `status` <= '3' AND `id` > '" . $_REQUEST['Message'] . "' ORDER BY `datetime`";
	$rows = $SQL->selectall($query);
	if (is_array($rows)) {
		foreach ($rows as $key => $row) {
			if (is_array($row)) {
				$message = $row['id']; 
			}
		}
	}
	else {
		$message = '';
	}
	
	header('Content-type: text/xml; charset=utf-8');
	echo('<?xml version="1.0" encoding="utf-8"?>' . "\n");
?>
<Messages xmlns="urn:LiveHelp" ID="<?php echo($_REQUEST['ID']); ?>" Status="<?php echo($active); ?>" Email="<?php echo(xmlattribinvalidchars($email)); ?>" Server="<?php echo(xmlattribinvalidchars($server)); ?>" Department="<?php echo(xmlattribinvalidchars($department)); ?>" Question="<?php echo(xmlattribinvalidchars($question)); ?>">
<?php
if (is_array($rows)) {
	foreach ($rows as $key => $row) {
		if (is_array($row)) {
		
			$id = $row['id'];
			$session = $row['session']; 
			$username = $row['username'];
			$message = $row['message'];
			$align = $row['align'];
			$status = $row['status'];
			
			// Outputs sent message
			if ($status) {
?>
<Message ID="<?php echo($id); ?>" Align="<?php echo($align); ?>" Status="<?php echo($status); ?>" Username="<?php echo(xmlattribinvalidchars($username)); ?>"><?php echo(xmlelementinvalidchars($message)); ?></Message>
<?php
			} else {	// Outputs received message
?>
<Message ID="<?php echo($id); ?>" Align="<?php echo($align); ?>" Status="<?php echo($status); ?>" Username="<?php echo(xmlattribinvalidchars($username)) ?>"><?php echo(xmlelementinvalidchars($message)); ?></Message>
<?php
			}
		}
	}
}
?>
</Messages>
<?php

}

function Chat() {

	global $_OPERATOR;
	global $_SETTINGS;
	global $SQL;
	global $table_prefix;

	if (!isset($_REQUEST['ID'])){ $_REQUEST['ID'] = ''; }
	if (!isset($_REQUEST['Message'])){ $_REQUEST['Message'] = ''; }
	if (!isset($_REQUEST['Staff'])){ $_REQUEST['Staff'] = ''; }
	if (!isset($_REQUEST['Typing'])){ $_REQUEST['Typing'] = ''; }

	if (!$_REQUEST['Staff']) {
		$query = "SELECT `active`, `typing` FROM " . $table_prefix . "sessions WHERE `id` = '" . $_REQUEST['ID'] . "'";
		$row = $SQL->selectquery($query);
		if (is_array($row)) {
			$active = $row['active'];
			$typing = $row['typing'];
			
			if ($_REQUEST['Typing']) { // Currently Typing
				switch($typing) {
				case 0: // None
					$typingresult = 2;
					break;
				case 1: // Guest Only
					$typingresult = 3;
					break;
				case 2: // Operator Only
					$typingresult = 2;
					break;
				case 3: // Both
					$typingresult = 3;
					break;		
				}
			}
			else { // Not Currently Typing
				switch($typing) {
				case 0: // None
					$typingresult = 0;
					break;
				case 1: // Guest Only
					$typingresult = 1;
					break;
				case 2: // Operator Only
					$typingresult = 0;
					break;
				case 3: // Both
					$typingresult = 1;
					break;		
				}
			}
				
			// Update the typing status of the specified chatting visitor
			$query = "UPDATE " . $table_prefix . "sessions SET `typing` = '$typingresult' WHERE `id` = '" . $_REQUEST['ID'] . "'";
			$SQL->miscquery($query);
		}
	}
	else {
		$active = '-1';
		$typingresult = '0';
	}
	
	if ($_REQUEST['Staff']) {
		$query = "SELECT `username` FROM " . $table_prefix . "users WHERE `id` = '" . $_REQUEST['ID'] . "'";
		$row = $SQL->selectquery($query);
		if (is_array($row)) {
			$operator_username = $row['username'];
		}
		$query = "SELECT `id`, `user`, `username`, `message`, `align`, `status` FROM " . $table_prefix . "administration WHERE ((`user` = '" . $_REQUEST['ID'] . "' AND `username` = '" . $_OPERATOR['USERNAME'] . "') OR (`user` = '" . $_OPERATOR['ID'] . "' AND `username` = '$operator_username')) AND `status` <= '3' AND `id` > '" . $_REQUEST['Message'] . "' AND (UNIX_TIMESTAMP(`datetime`) - UNIX_TIMESTAMP('" . $_OPERATOR['DATETIME'] . "')) > '0' ORDER BY `datetime`";
	}
	else {
		$query = "SELECT `id`, `session`, `username`, `message`, `align`, `status` FROM " . $table_prefix . "messages WHERE `session` = '" . $_REQUEST['ID'] . "' AND `status` <= '3' AND `id` > '" . $_REQUEST['Message'] . "' ORDER BY `datetime`";
	}
	$rows = $SQL->selectall($query);
	if (is_array($rows)) {
		foreach ($rows as $key => $row) {
			if (is_array($row)) {
				$message = $row['id']; 
			}
		}
	}
	else {
		$message = '';
	}
	
	header('Content-type: text/xml; charset=utf-8');
	echo('<?xml version="1.0" encoding="utf-8"?>' . "\n");
?>
<Messages xmlns="urn:LiveHelp" ID="<?php echo($_REQUEST['ID']); ?>" Typing="<?php echo($typingresult); ?>" Status="<?php echo($active); ?>">
<?php
if (is_array($rows)) {
	foreach ($rows as $key => $row) {
		if (is_array($row)) {
		
			if ($_REQUEST['Staff']) {
				$session = $row['user'];
			}
			else {
				$session = $row['session']; 
			}
			$id = $row['id'];
			$username = $row['username'];
			$message = $row['message'];
			$align = $row['align'];
			$status = $row['status'];
			
			// Outputs sent message
			if ((!$_REQUEST['Staff'] && $status) || ($_REQUEST['Staff'] && $session == $_REQUEST['ID'] && $row['username'] == $_OPERATOR['USERNAME'])) {
?>
<Message ID="<?php echo($id); ?>" Align="<?php echo($align); ?>" Status="<?php echo($status); ?>" Username="<?php echo(xmlattribinvalidchars($username)); ?>"><?php echo(xmlelementinvalidchars($message)); ?></Message>
<?php
			}
			// Outputs received message
			if ((!$_REQUEST['Staff'] && !$status) || ($_REQUEST['Staff'] && $session == $_OPERATOR['ID'] && $row['username'] == $operator_username)) {
?>
<Message ID="<?php echo($id); ?>" Align="<?php echo($align); ?>" Status="<?php echo($status); ?>" Username="<?php echo(xmlattribinvalidchars($username)) ?>"><?php echo(xmlelementinvalidchars($message)); ?></Message>
<?php
			}
		}
	}
}
?>
</Messages>
<?php

}

function Operators() {

	global $_OPERATOR;
	global $SQL;
	global $table_prefix;

	if (!isset($_REQUEST['ID'])){ $_REQUEST['ID'] = ''; }
	if (!isset($_REQUEST['User'])){ $_REQUEST['User'] = ''; }
	if (!isset($_REQUEST['Firstname'])){ $_REQUEST['Firstname'] = ''; }
	if (!isset($_REQUEST['Lastname'])){ $_REQUEST['Lastname'] = ''; }
	if (!isset($_REQUEST['CurrentPassword'])){ $_REQUEST['CurrentPassword'] = ''; }
	if (!isset($_REQUEST['NewPassword'])){ $_REQUEST['NewPassword'] = ''; }
	if (!isset($_REQUEST['Email'])){ $_REQUEST['Email'] = ''; }
	if (!isset($_REQUEST['Department'])){ $_REQUEST['Department'] = ''; }
	if (!isset($_REQUEST['Privilege'])){ $_REQUEST['Privilege'] = ''; }
	if (!isset($_REQUEST['Disabled'])){ $_REQUEST['Disabled'] = ''; }
	if (!isset($_REQUEST['Status'])){ $_REQUEST['Status'] = ''; }
	
	header('Content-type: text/xml; charset=utf-8');
	echo('<?xml version="1.0" encoding="utf-8"?>' . "\n");
	
	if ($_REQUEST['ID'] != '') {
	
		// If editing own operator details 
		if ($_OPERATOR['ID'] == $_REQUEST['ID']) {
		
			// Can't change permission to lower value - higher administration rights
			if ($_REQUEST['Privilege'] < $_OPERATOR['PRIVILEGE']) {
				$_REQUEST['Privilege'] = $_OPERATOR['PRIVILEGE'];
			}
		}
		else {
			// If NOT an Administrator
			if ($_OPERATOR['PRIVILEGE'] > 1) {
?>
<Operators xmlns="urn:LiveHelp" />
<?php
				exit();
			}
		}
	
		// Update an existing account
		if ($_REQUEST['ID'] != '' && $_REQUEST['User'] != '' && $_REQUEST['Firstname'] != '' && $_REQUEST['Email'] != '' && $_REQUEST['Department'] != '' && $_REQUEST['Privilege'] != '' && $_REQUEST['Disabled'] != '') {
	
			$query = "UPDATE " . $table_prefix . "users SET `username` = '" . $_REQUEST['User'] . "', `firstname` = '" . $_REQUEST['Firstname'] . "', `lastname` = '" . $_REQUEST['Lastname'] . "', `email` = '" . $_REQUEST['Email'] . "', `department` = '" . $_REQUEST['Department'] . "', `privilege` = '" . $_REQUEST['Privilege'] . "', `disabled` = '" . $_REQUEST['Disabled'] . "' WHERE `id` = '" . $_REQUEST['ID'] . "'";
			$result = $SQL->miscquery($query);
			if ($result == false) {
?>
<Operators xmlns="urn:LiveHelp" />
<?php
				exit();
			}
	
		}
		elseif ($_REQUEST['CurrentPassword'] != '' && $_REQUEST['NewPassword'] != '') {  // Change password
		
			// Confirm current password is correct before updating
			$query = "SELECT `id` FROM " . $table_prefix . "users WHERE `id` = '" . $_REQUEST['ID'] . "' AND `password` = '" . $_REQUEST['CurrentPassword'] . "'";
			$row = $SQL->selectquery($query);
			if (is_array($row)) {
		
				$query = "UPDATE " . $table_prefix . "users SET `password` = '" . $_REQUEST['NewPassword'] . "' WHERE `id` = '" . $_REQUEST['ID'] . "'";
				$result = $SQL->miscquery($query);
				if ($result == false) {
?>
<Operators xmlns="urn:LiveHelp" />
<?php
					exit();
				}
				
			}
			else {
?>
<Operators xmlns="urn:LiveHelp" />
<?php
				exit();
			}
		}
		else {  // Delete operator
		
			$query = "DELETE FROM " . $table_prefix . "users WHERE `id` = '" . $_REQUEST['ID'] . "'";
			$result = $SQL->miscquery($query);
			if ($result == false) {
?>
<Operators xmlns="urn:LiveHelp" />
<?php
				exit();
			}
		
		} 
	}
	else {
	
		// If current operator is an administrator
		if ($_OPERATOR['PRIVILEGE'] < 2) {
	
			// Add a new account
			if ($_REQUEST['User'] != '' && $_REQUEST['Firstname'] != '' && $_REQUEST['NewPassword'] != '' && $_REQUEST['Email'] != '' && $_REQUEST['Department'] != '' && $_REQUEST['Privilege'] != '' && $_REQUEST['Disabled'] != '') {
		
				$query = "INSERT INTO " . $table_prefix . "users(`username`, `firstname`, `lastname`, `password`, `email`, `department`, `privilege`, `disabled`) VALUES('" . $_REQUEST['User'] . "', '" . $_REQUEST['Firstname'] . "', '" . $_REQUEST['Lastname'] . "', '" . $_REQUEST['NewPassword'] . "', '" . $_REQUEST['Email'] . "', '" . $_REQUEST['Department'] . "', '" . $_REQUEST['Privilege'] . "', '" . $_REQUEST['Disabled'] . "')";
				$result = $SQL->miscquery($query);
				if ($result == false) {
?>
<Operators xmlns="urn:LiveHelp" />
<?php
					exit();
				}
			}
		}
		
	}
	
	$query = "SELECT * FROM " . $table_prefix . "users ORDER BY `username`";
	$rows = $SQL->selectall($query);
	if (is_array($rows)) {
?>
<Operators xmlns="urn:LiveHelp">
<?php
		foreach ($rows as $key => $row) {
			if (is_array($row)) {
				$operator_id = $row['id'];
				$operator_username = $row['username'];
				$operator_firstname = $row['firstname'];
				$operator_lastname = $row['lastname'];
				$operator_email = $row['email'];
				$operator_password = $row['password'];
				$operator_department = $row['department'];
				$operator_datetime = $row['datetime'];
				$operator_refresh = $row['refresh'];
				$operator_privilege = $row['privilege'];
				$operator_disabled = $row['disabled'];
				$operator_status = $row['status'];
?>
<Operator ID="<?php echo($operator_id); ?>">
<Username><?php echo(xmlelementinvalidchars($operator_username)); ?></Username>
<Firstname><?php echo($operator_firstname); ?></Firstname>
<Lastname><?php echo(xmlelementinvalidchars($operator_lastname)); ?></Lastname>
<Email><?php echo(xmlelementinvalidchars($operator_email)); ?></Email>
<Password><?php echo(xmlelementinvalidchars($operator_password)); ?></Password>
<Department><?php echo(xmlelementinvalidchars($operator_department)); ?></Department>
<Datetime><?php echo(xmlelementinvalidchars($operator_datetime)); ?></Datetime>
<Refresh><?php echo(xmlelementinvalidchars($operator_refresh)); ?></Refresh>
<Privilege><?php echo($operator_privilege); ?></Privilege>
<Disabled><?php echo($operator_disabled); ?></Disabled>
<Status><?php echo(xmlelementinvalidchars($operator_status)); ?></Status>
</Operator>
<?php
			}
		}
?>
</Operators>
<?php
	}
	else {
?>
<Operators xmlns="urn:LiveHelp"/>
<?php
	}
}

function Statistics() {

	global $_OPERATOR;
	global $_SETTINGS;
	global $SQL;
	global $table_prefix;

	header('Content-type: text/xml; charset=utf-8');
	echo('<?xml version="1.0" encoding="utf-8"?>' . "\n");

?>
<Statistics xmlns="urn:LiveHelp">
<?php
	
	$query = "SELECT DISTINCT `rating`, count(`id`) AS total FROM " . $table_prefix . "sessions WHERE DATE_FORMAT(`datetime`, '%M') = DATE_FORMAT(NOW(), '%M') GROUP BY `rating` ORDER BY `rating` DESC";
	$rows = $SQL->selectall($query);
	if (is_array($rows)) {
?>
<Rating>
<?php
		foreach($rows as $key => $row) {
			if (is_array($row)) {
				
				$rating = $row['rating'];
				$total = $row['total'];
				
				switch($rating) {
				case 5:
?>
<Excellent><?php echo($total); ?></Excellent>
<?php
					break;
				case 4:
?>
<VeryGood><?php echo($total); ?></VeryGood>
<?php
					break;
				case 3:
?>
<Good><?php echo($total); ?></Good>
<?php
					break;
				case 2:
?>
<Average><?php echo($total); ?></Average>
<?php
					break;
				case 1:
?>
<Poor><?php echo($total); ?></Poor>
<?php
					break;
				}
			}
		}
?>
</Rating>
<?php
	}
	else {
?>
<Rating />
<?php
	}
	
	$query = "SELECT DISTINCT `referrer`, count(`id`) AS total FROM " . $table_prefix . "requests WHERE DATE_FORMAT(`datetime`, '%M') = DATE_FORMAT(NOW(), '%M') AND `referrer` NOT LIKE '%" . $_SETTINGS['DOMAIN'] . "%' GROUP BY `referrer` ORDER BY total DESC LIMIT 0, 5";
	$rows = $SQL->selectall($query);
	if (is_array($rows)) {
?>
<Referrers>
<?php
		foreach($rows as $key => $row) {
			if (is_array($row)) {
				$url = $row['referrer'];
				$total = $row['total'];
?>
<Referrer Total="<?php echo($total); ?>"><?php echo(xmlelementinvalidchars($url)); ?></Referrer>
<?php
			}
		}
?>
</Referrers>
<?php
	}
	else {
?>
<Referrers />
<?php
	}
?>
</Statistics>
<?php

}

function History() {

	global $_OPERATOR;
	global $SQL;
	global $table_prefix;

	if (!isset($_REQUEST['Date'])){ $_REQUEST['Date'] = ''; }
	if (!isset($_REQUEST['Timezone'])){ $_REQUEST['Timezone'] = ''; }
	if (!isset($_REQUEST['Transcripts'])){ $_REQUEST['Transcripts'] = ''; }

	header('Content-type: text/xml; charset=utf-8');
	echo('<?xml version="1.0" encoding="utf-8"?>' . "\n");
	
	// Save Settings if authorized
	if ($_OPERATOR['PRIVILEGE'] > 2) {
		if ($_REQUEST['Transcripts'] != '') {
?>
<ChatHistory xmlns="urn:LiveHelp"/>
<?php
		}
		else {
?>
<VisitorHistory xmlns="urn:LiveHelp"/>
<?php
		}
	exit();
	}

	list($year, $month, $day) = split('-', $_REQUEST['Date']);

	$timezone = date('O');
	if ($timezone != $_REQUEST['Timezone']) {
	
		$sign = substr($_REQUEST['Timezone'], 0, 1);
		$hours = substr($_REQUEST['Timezone'], -4, 2);
		$minutes = substr($_REQUEST['Timezone'], -2, 4);
		if ($minutes != 0) { $minutes = ($minutes / 0.6); }
		$local = $sign . $hours . $minutes;
	
		$sign = substr($timezone, 0, 1);
		$hours = substr($timezone, 1, 2);
		$minutes = substr($timezone, 3, 4);
		if ($minutes != 0) { $minutes = ($minutes / 0.6); }
		$remote = $sign . $hours . $minutes;
	
		// Convert to eg. +/-0430 format
		$hours = substr(sprintf("%04d", $local - $remote), 0, 2);
		$minutes = substr(sprintf("%04d", $local - $remote), 2, 4);
		if ($minutes != 0) { $minutes = ($minutes * 0.6); }
		$difference = ($hours * 60 * 60) + ($minutes * 60);
		
		$from = date('Y-m-d H:i:s', mktime(0 - $hours, 0 - $minutes, 0, $month, $day, $year));
		$to = date('Y-m-d H:i:s', mktime(0 - $hours, 0 - $minutes, 0, $month, $day + 1, $year));
		
		if ($difference != 0) {
		
			$from = date('Y-m-d H:i:s', mktime(0 - $hours, 0 - $minutes, 0, $month, $day, $year));
			$to = date('Y-m-d H:i:s', mktime(0 - $hours, 0 - $minutes, 0, $month, $day + 1, $year));
			$query = "SELECT *, DATE_ADD(`datetime`, INTERVAL '$hours:$minutes' HOUR_MINUTE) AS `timezone` FROM " . $table_prefix . "requests WHERE `datetime` > '$from' AND `datetime` < '$to' AND `status` = '0' ORDER BY `request`";

		} else {
		
			$from = date('Y-m-d H:i:s', mktime(0, 0, 0, $month, $day, $year));
			$to = date('Y-m-d H:i:s', mktime(24, 0, 0, $month, $day, $year));
			$query = "SELECT *, `datetime` AS `timezone` FROM " . $table_prefix . "requests WHERE `datetime` > '$from' AND `datetime` < '$to' AND `status` = '0' ORDER BY `request`";
		}
		

	} else {
	
		$from = date('Y-m-d H:i:s', mktime(0, 0, 0, $month, $day, $year));
		$to = date('Y-m-d H:i:s', mktime(24, 0, 0, $month, $day, $year));
	
		$query = "SELECT *, `datetime` AS `timezone` FROM " . $table_prefix . "requests WHERE `datetime` > '$from' AND `datetime` < '$to' AND `status` = '0' ORDER BY `request`";
	}

	$rows = $SQL->selectall($query);
	if (is_array($rows)) {
		if ($_REQUEST['Transcripts'] != '') {
?>
<ChatHistory xmlns="urn:LiveHelp">
<?php
		}
		else {
?>
<VisitorHistory xmlns="urn:LiveHelp">
<?php
		}
		
		$rating_label = 'Rating';			
	
		foreach ($rows as $key => $row) {
			if (is_array($row)) {
				$current_request_id = $row['id'];
				$current_request_ip_address = $row['ipaddress'];
				$current_request_user_agent = $row['useragent'];
				$current_request_referer = $row['referrer'];
				$current_request_current_page = $row['url'];
				$current_request_page_path = $row['path'];
				$current_request_datetime = $row['timezone'];
	
				if ($_REQUEST['Transcripts'] != '') {
	
					// Get the supporters name of the chat request if currently chatting.
					$query = "SELECT sessions.id, sessions.username, messages.username AS operator, `department`, `rating`, `active`, ((UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(sessions.datetime))) AS `sitetime` FROM " . $table_prefix . "sessions AS sessions, " . $table_prefix . "messages AS messages WHERE sessions.id = messages.session AND `status` = '1' AND `request` = '" . $current_request_id . "' ORDER BY sessions.datetime DESC LIMIT 1";
					$row = $SQL->selectquery($query);
					if (is_array($row)) {
		
						$current_session_id = $row['id'];
						$current_session_username = $row['username'];
						$current_session_operator = $row['operator'];
						$current_session_department = $row['department'];
						$current_session_rating = $row['rating'];
						$current_session_active = $row['active'];
						$current_session_sitetime = $row['sitetime'];
							
						if ($current_session_sitetime > 45) {
							// Get the supporters name of the chat request if currently chatting.
							$query = "SELECT `firstname`, `lastname` FROM " . $table_prefix . "users WHERE `username` = '$current_session_operator'";
							$row = $SQL->selectquery($query);
							if (is_array($row)) {
							
								$current_session_operator_name = $row['firstname'] . ' ' . $row['lastname'];
		
							}
						}
						
?>
<Visitor ID="<?php echo($current_request_id); ?>" Session="<?php echo($current_session_id); ?>" Active="<?php echo($current_session_active); ?>" Username="<?php echo(xmlattribinvalidchars($current_session_username)); ?>">
<Hostname><?php echo(xmlelementinvalidchars($current_request_ip_address)); ?></Hostname>
<UserAgent><?php echo(xmlelementinvalidchars($current_request_user_agent)); ?></UserAgent>
<CurrentPage><?php echo(xmlelementinvalidchars($current_request_current_page)); ?></CurrentPage>
<SiteTime><?php echo($current_request_datetime); ?></SiteTime>
<PagePath><?php echo(xmlelementinvalidchars($current_request_page_path)); ?></PagePath>
<Operator><?php echo(xmlelementinvalidchars($current_session_operator_name)); ?></Operator>
<Department><?php echo(xmlelementinvalidchars($current_session_department)); ?></Department>
<Rating><?php echo(xmlelementinvalidchars($current_session_rating)); ?></Rating>
</Visitor>
<?php
						
					}
	
				}
				else {
?>
<Visitor ID="<?php echo($current_request_id); ?>">
<Hostname><?php echo(xmlelementinvalidchars($current_request_ip_address)); ?></Hostname>
<UserAgent><?php echo(xmlelementinvalidchars($current_request_user_agent)); ?></UserAgent>
<CurrentPage><?php echo(xmlelementinvalidchars($current_request_current_page)); ?></CurrentPage>
<SiteTime><?php echo($current_request_datetime); ?></SiteTime>
<Referrer><?php echo(xmlelementinvalidchars($current_request_referer)); ?></Referrer>
</Visitor>
<?php
				}
	
			}
		}
		if ($_REQUEST['Transcripts'] != '') {
		
			if ($timezone != $_REQUEST['Timezone']) {
				$query = "SELECT sessions.id, sessions.username, users.firstname, users.lastname, DATE_ADD(sessions.datetime, INTERVAL '$hours:$minutes' HOUR_MINUTE) AS datetime, sessions.department, `rating`, `active` FROM " . $table_prefix . "sessions AS sessions, " . $table_prefix . "messages AS messages, " . $table_prefix . "users AS users WHERE messages.username = users.username AND messages.session = sessions.id AND sessions.request = '0' AND sessions.datetime > '$from' AND sessions.datetime < '$to' AND messages.status = '1' LIMIT 1";
			} else {
				$query = "SELECT sessions.id, sessions.username, users.firstname, users.lastname, sessions.datetime, sessions.department, `rating`, `active` FROM " . $table_prefix . "sessions AS sessions, " . $table_prefix . "messages AS messages, " . $table_prefix . "users AS users WHERE messages.username = users.username AND messages.session = sessions.id AND sessions.request = '0' AND sessions.datetime > '$from' AND sessions.datetime < '$to' AND messages.status = '1' LIMIT 1";
			}
			$rows = $SQL->selectall($query);
			if (is_array($rows)) {
				foreach ($rows as $key => $row) {
					if (is_array($row)) {
					
						$current_request_id = -1;
						$current_session_id = $row['id'];
						$current_session_active = $row['active'];
						$current_session_username = $row['username'];
						$current_request_ip_address = 'Unavailable';
						$current_request_user_agent = 'Unavailable';
						$current_request_current_page = 'Unavailable';
						$current_request_datetime =  $row['datetime'];
						$current_request_page_path = 'Unavailable';
						$current_session_operator_name = $row['firstname'] . ' ' . $row['lastname'];
						$current_session_department = $row['department'];
						$current_session_rating = $row['rating'];
						
?>
<Visitor ID="<?php echo($current_request_id); ?>" Session="<?php echo($current_session_id); ?>" Active="<?php echo($current_session_active); ?>" Username="<?php echo(xmlattribinvalidchars($current_session_username)); ?>">
<Hostname><?php echo(xmlelementinvalidchars($current_request_ip_address)); ?></Hostname>
<UserAgent><?php echo(xmlelementinvalidchars($current_request_user_agent)); ?></UserAgent>
<CurrentPage><?php echo(xmlelementinvalidchars($current_request_current_page)); ?></CurrentPage>
<SiteTime><?php echo($current_request_datetime); ?></SiteTime>
<PagePath><?php echo(xmlelementinvalidchars($current_request_page_path)); ?></PagePath>
<Operator><?php echo(xmlelementinvalidchars($current_session_operator_name)); ?></Operator>
<Department><?php echo(xmlelementinvalidchars($current_session_department)); ?></Department>
<Rating><?php echo(xmlelementinvalidchars($current_session_rating)); ?></Rating>
</Visitor>
<?php
					}
				}
			}
		
?>
</ChatHistory>
<?php
		}
		else {
?>
</VisitorHistory>
<?php
		}
	}
	else {
		if ($_REQUEST['Transcripts'] != '') {
?>
<ChatHistory xmlns="urn:LiveHelp"/>
<?php
		}
		else {
?>
<VisitorHistory xmlns="urn:LiveHelp"/>
<?php
		}
	}
}

function Send() {

	global $_OPERATOR;
	global $SQL;
	global $table_prefix;

	if (!isset($_REQUEST['ID'])){ $_REQUEST['ID'] = ''; }
	if (!isset($_REQUEST['Message'])){ $_REQUEST['Message'] = ''; }
	if (!isset($_REQUEST['Staff'])){ $_REQUEST['Staff'] = ''; }
	if (!isset($_REQUEST['Type'])){ $_REQUEST['Type'] = ''; }
	if (!isset($_REQUEST['Name'])){ $_REQUEST['Name'] = ''; }
	if (!isset($_REQUEST['Content'])){ $_REQUEST['Content'] = ''; }
	
	$result = '0';
	
	// Check if the message contains any content else return headers
	if ($_REQUEST['Message'] == '' && $_REQUEST['Type'] == '' && $_REQUEST['Name'] == '' && $_REQUEST['Content'] == '') {
		header('Content-type: text/xml; charset=utf-8');
		echo('<?xml version="1.0" encoding="utf-8"?>' . "\n");
?>
<SendMessage xmlns="urn:LiveHelp"/>
<?php
		exit();
	}
	

	if ($_REQUEST['Type'] != '' && $_REQUEST['Name'] != '' && $_REQUEST['Content'] != '') {
	
		// Strip the slashes because slashes will be added to whole string
		$type = $_REQUEST['Type'];
		$name = stripslashes(trim($_REQUEST['Name']));
		$content = stripslashes(trim($_REQUEST['Content']));
		$operator = '';
		
		switch ($type) {
			case 'LINK':
				$type = 2;
				$command = addslashes($name . " \r\n " . $content);
				break;
			case 'IMAGE':
				$type = 3;
				$command = addslashes($name . " \r\n " . $content);
				break;
			case 'PUSH':
				$type = 4;
				$command = addslashes($content);
				$operator = addslashes('The ' . $name . ' has been PUSHed to the visitor.');
				break;
			case 'JAVASCRIPT':
				$type = 5;
				$command = addslashes($content);
				$operator = addslashes('The ' . $name . ' has been sent to the visitor.');
				break;
		}
		
		if ($command != '') {
			$query = "INSERT INTO " . $table_prefix . "messages (`session`, `username`, `datetime`, `message`, `align`, `status`) VALUES ('" . $_REQUEST['ID'] . "', '', NOW(), '$command', '2', '$type')";
			if ($operator != '') {
				$query .= ", ('" . $_REQUEST['ID'] . "', '', NOW(), '$operator', '2', '-1')";
			}
			$id = $SQL->insertquery($query);
			if ($id != false) {
				$result = '1';
			}
		}
		
	}
	
	// Format the message string
	$message = trim($_REQUEST['Message']);
		
	if ($message != '') {
		if (!$_REQUEST['Staff']) {
			// Send messages from POSTed data
			$query = "INSERT INTO " . $table_prefix . "messages (`session`, `username`, `datetime`, `message`, `align`, `status`) VALUES('" . $_REQUEST['ID'] . "', '" . $_OPERATOR['USERNAME'] . "', NOW(), '" . $_REQUEST['Message'] . "', '1', '1')";
			$id = $SQL->insertquery($query);
			if ($id != false) {
				$result = '1';
			}
		}
		else {
			$query = "INSERT INTO " . $table_prefix . "administration (`user`, `username`, `datetime`, `message`, `align`, `status`) VALUES('" . $_REQUEST['ID'] . "', '" . $_OPERATOR['USERNAME'] . "', NOW(), '" . $_REQUEST['Message'] . "', '1', '1')";
			$id = $SQL->insertquery($query);
			if ($id != false) {
				$result = '1';
			}
		}
	}
	
	header('Content-type: text/xml; charset=utf-8');
	echo('<?xml version="1.0" encoding="utf-8"?>' . "\n");
?>
<SendMessage xmlns="urn:LiveHelp" Result="<?php echo($result); ?>"></SendMessage>
<?php

}

function EmailChat() {

	global $_OPERATOR;
	global $_SETTINGS;
	global $SQL;
	global $table_prefix;

	if (!isset($_REQUEST['ID'])){ $_REQUEST['ID'] = ''; }

	if ($_SETTINGS['SMTP'] == true) {
		ini_set('SMTP', $_SETTINGS['SMTPSERVER']);
		ini_set('smtp_port', $_SETTINGS['SMTPPORT']);
		ini_set('sendmail_from', $_SETTINGS['SMTPEMAIL']);
	}

	// Determine EOL
	$server = strtoupper(substr($_SERVER['OS'], 0, 3));
	if ($server == 'WIN') { 
		$eol = "\r\n"; 
	} elseif ($server == 'MAC') { 
		$eol = "\r"; 
	} else { 
		$eol = "\n"; 
	}

	# Boundry for marking the split & Multitype Headers 
	$mime_boundary = md5(time());
	$subject = '=?UTF-8?B?' . base64_encode($_SETTINGS['NAME'] . ' Chat Transcript') . '?=';
					
	$headers = 'From: "=?UTF-8?B?' . base64_encode($_SETTINGS['NAME']) . '?=" <' . $_SETTINGS['EMAIL'] . '>' . $eol;
	$headers .= 'Reply-To: <' . $_SETTINGS['EMAIL'] . '>' . $eol;
	$headers .= 'Return-Path: <' . $_SETTINGS['EMAIL'] . '>' . $eol;
	$headers .= 'MIME-Version: 1.0' . $eol; 
	$headers .= 'Content-Type: multipart/alternative; boundary="' . $mime_boundary . '"' . $eol; 
	

	$query = "SELECT `username`, `message`, `status` FROM " . $table_prefix . "messages WHERE `session` = '" . $_REQUEST['ID'] . "' AND `status` <= '3' ORDER BY `datetime`";
	$rows = $SQL->selectall($query);
	if (is_array($rows)) {
	
		$htmlmessages = ''; $textmessages = '';
		foreach ($rows as $key => $row) {
			if (is_array($row)) {
			
				$username = $row['username'];
				$message = $row['message'];
				$status = $row['status'];
				
				// Operator
				if ($status) {
					$htmlmessages .= '<div style="color:#666666">' . $username . ' says:</div><div style="margin-left:15px; color:#666666;">' . $message . '</div>'; 
					$textmessages .= $username . ' says:' . $eol . '	' . $message . $eol; 
				}
				// Guest
				if (!$status) {
					$htmlmessages .= '<div>' . $username . ' says:</div><div style="margin-left: 15px;">' . $message . '</div>'; 
					$textmessages .= $username . ' says:' . $eol . '	' . $message . $eol; 
				}
			}
		}
	}

	$htmlmessages = preg_replace("/(\r\n|\r|\n)/", '<br/>', $htmlmessages);
	
	// Add Plain Text Email
	$body = '--' . $mime_boundary . $eol;
	$body .= 'Content-type: text/plain; charset=utf-8' . $eol . $eol;
	$body .= $textmessages . $eol . $eol;
	
	
	$html = <<<END
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
<!--

div, p {
	font-family: Calibri, Verdana, Arial, Helvetica, sans-serif;
	font-size: 14px;
	color: #000000;
}

//-->
</style>
</head>

<body>
<p><img src="{$_SETTINGS['URL']}/livehelp/locale/en/images/ChatTranscript.gif" width="531" height="79" alt="Chat Transcript" /></p>
<p><strong>Chat Transcript:</strong></p>
<p>$htmlmessages</p>
<p><img src="{$_SETTINGS['URL']}/livehelp/locale/en/images/LogoSmall.png" width="217" height="52" alt="stardevelop.com" /></p>
</body>
</html>
END;
	
	// Add HTML Email
	$body .= '--' . $mime_boundary . $eol;
	$body .= 'Content-type: text/html; charset=utf-8' . $eol . $eol;
	$body .= $html . $eol . $eol;
	$body .= "--" . $mime_boundary . "--" . $eol . $eol;
	
	$sendmail_path = ini_get('sendmail_path');
	mail($_SETTINGS['EMAIL'], $subject, $body, $headers);


}

?>